<?php

namespace app\admin\controller\org;

use app\admin\controller\Zlog;
use app\common\controller\Backend;
use app\admin\model\org\Orgcate;
use fast\tree;
use think\Db;

/**
 * 年纪班级管理
 *
 * @icon fa fa-circle-o
 */
class Orggrade extends Backend
{
    
    /**
     * Orggrade模型对象
     * @var \app\admin\model\org\Orggrade
     */
    protected $model = null;
    protected $searchFields = 'name';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\org\Orggrade;
        $this->view->assign("statusList", $this->model->getStatusList());

        $org_where = [];
        $org_whereor = [];
        $grade_where = [];
        if(ORG_CATE_ID > 0){
            $child_org_ids = Orgcate::where('parent_id', ORG_CATE_ID)->column('id');
            $org_where = array('parent_id' => array( ['=', ORG_CATE_ID], ['in', $child_org_ids], 'or'));
            $org_whereor = array('id'=>ORG_CATE_ID);
            
            $child_org_ids[] = ORG_CATE_ID;
            $grade_where = array('org_cate_id' => ['in', $child_org_ids]);
            
        }
        $this->grade_where = $grade_where;
        $orgcateList = collection(Orgcate::where($org_where)->whereOr($org_whereor)->select())->toArray();

        $orgcat = [];
        foreach($orgcateList as $k => $v){
            $orgcat[$v['id']] = $v['name'];
        }
        
        $this->orgcat = $orgcat;
        
        Tree::instance()->init($orgcateList, 'parent_id');
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $orgName_tree = [];
        foreach($result as $k => $v){
            $orgName_tree[$v['id']] = $v['name'];
        }
        $this->orgName_tree = $orgName_tree;

        
        $gradeList = collection($this->model->where($grade_where)->select())->toArray();
        
        $grade = [];
        foreach($gradeList as $k => $v){
            $grade[$v['id']] = $v['name'];
            if(ORG_CATE_ID == 0) $gradeList[$k]['name'] = $v['name'].'('.$orgcat[$v['org_cate_id']].')';
        }
        $this->grade = $grade;
        Tree::instance()->init($gradeList, 'parent_id');
        $result2 = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $grade_tree = [];
        foreach($result2 as $k => $v){
            $grade_tree[$v['id']] = $v['name'];
        }
        $this->orgGrade_tree = $grade_tree;

        $this->view->assign('orgGrade_tree', $grade_tree);

        $this->view->assign('orgName_tree', $orgName_tree);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->where($where)
                    ->where($this->grade_where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                     ->where($this->grade_where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();

            foreach($list as $k => $v){
                $list[$k]['org_cate_id'] = $this->orgcat[$v['org_cate_id']];
                if($v['parent_id'] == 0){
                    $list[$k]['parent_id'] = '顶级';
                }else{
                    $list[$k]['parent_id'] = $this->grade[$v['parent_id']];
                }
            }
            
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function add(){
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                $level = Db::name('org_cate')->where('id', $params['org_cate_id'])->value('level');
                if($level != 3){
                    $this->error('请选择三级单位');
                }
                if($params['level'] == 2){
                    if($params['parent_id'] == 0){
                        $this->error('班级请选择对应年级！');
                    }
                }
                if($params['parent_id'] != 0){
                    $parent_info = $this->model->field('org_cate_id')->where('id', $params['parent_id'])->find();
                    if($params['org_cate_id'] != $parent_info['org_cate_id']){
                        $this->error('组织与上级组织不一致');
                    }
                }
                $result = $this->model->validate('app\admin\validate\org\Orggrade.add')->save($params);
                if ($result === false)
                {
                    $this->error($this->model->getError());
                }
                
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                $level = Db::name('org_cate')->where('id', $params['org_cate_id'])->value('level');
                if($level != 3){
                    $this->error('请选择三级单位');
                }
                if($params['level'] == 2){
                    $count = Db::name('org_grade')->where('parent_id', $ids)->count('id');
                    if($count > 0){
                        $this->error('请先处理该等级下的班级！');
                    }
                    if($params['parent_id'] == 0){
                        $this->error('班级请选择对应年级！');
                    }
                }
                if($params['parent_id'] == $ids){
                    $this->error('上级信息有误');
                }
                if($params['parent_id'] != 0) {
                    $parent_info = $this->model->field('parent_id, org_cate_id')->where('id', $params['parent_id'])->find();
                    if ($parent_info && $parent_info['parent_id'] == $ids) {
                        $this->error('上级信息有误');
                    }

                    if ($params['org_cate_id'] != $parent_info['org_cate_id']) {
                        $this->error('组织与上级组织不一致');
                    }
                }
                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $groups = Db::name('org_grade')->where('org_cate_id',  $row['org_cate_id'])->where('level', 1)->select();
        $this->view->assign("row", $row);
        $this->view->assign("groups", $groups);
        return $this->view->fetch();
    }
    

}
